package com.ruoyi.flow.common.tools.mediaconverter.converter.reflections.scanners;

import java.lang.reflect.Field;
import java.lang.reflect.Member;

import com.google.common.base.Joiner;
import com.ruoyi.flow.common.tools.mediaconverter.converter.reflections.util.JavaReflectionUtils;

/** scans fields and methods and stores fqn as key and elements as values */
@SuppressWarnings({"unchecked"})
public class TypeElementsScanner extends AbstractScanner {
    private boolean includeFields = true;
    private boolean includeMethods = true;
    private boolean includeAnnotations = true;
    private boolean publicOnly = true;

    public void scan(Class cls) {
        String className = JavaReflectionUtils.getClassName(cls);
        if (!acceptResult(className)) return;

        getStore().put(className, "");

        if (includeFields) {
            for (Field field : JavaReflectionUtils.getFields(cls)) {
                String fieldName = JavaReflectionUtils.getFieldName(field);
                getStore().put(className, fieldName);
            }
        }

        if (includeMethods) {
            for (Member method : JavaReflectionUtils.getMethods(cls)) {
                if (!publicOnly || JavaReflectionUtils.isPublic(method)) {
                    String methodKey = JavaReflectionUtils.getMethodName(method) + "(" +
                            Joiner.on(", ").join(JavaReflectionUtils.getParameterNames(method)) + ")";
                    getStore().put(className, methodKey);
                }
            }
        }

        if (includeAnnotations) {
            for (Object annotation : JavaReflectionUtils.getClassAnnotationNames(cls)) {
                getStore().put(className, "@" + annotation);
            }
        }
    }

    //
    public TypeElementsScanner includeFields() { return includeFields(true); }
    public TypeElementsScanner includeFields(boolean include) { includeFields = include; return this; }
    public TypeElementsScanner includeMethods() { return includeMethods(true); }
    public TypeElementsScanner includeMethods(boolean include) { includeMethods = include; return this; }
    public TypeElementsScanner includeAnnotations() { return includeAnnotations(true); }
    public TypeElementsScanner includeAnnotations(boolean include) { includeAnnotations = include; return this; }
    public TypeElementsScanner publicOnly(boolean only) { publicOnly = only; return this; }
    public TypeElementsScanner publicOnly() { return publicOnly(true); }
}
